/*
 * @Author: xiaosihan 
 * @Date: 2023-04-15 11:26:32 
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2023-04-15 12:38:09
 */

import html2canvas from "html2canvas";
import { CanvasTexture, Sprite } from "three";
import threeLoader from "./threeLoader";


// html 文本面板
export default class SpriteWithHtml extends Sprite {

    constructor(html: string = "", backgroundColor: `#${string}` = "#00000000") {
        super();
        this.setHtml(html, backgroundColor);
    }

    visible = false;

    div = (() => {
        const div = document.createElement("div");
        div.style.position = "fixed";
        div.style.top = "100%";
        div.style.left = "100%";
        div.style.pointerEvents = "none";
        div.style.userSelect = "none";
        div.style.lineHeight = "1";
        div.style.whiteSpace = "nowrap";
        return div;
    })();

    async setHtml(html: string = "", backgroundColor: `#${string}` = "#00000000") {
        this.div.innerHTML = html;
        document.body.appendChild(this.div);

        await new Promise<void>((resolve, reject) => {

            html2canvas(this.div, {
                backgroundColor,
                removeContainer: true
            }).then(async (canvas) => {
                this.scale.set(canvas.width, canvas.height, 1);
                this.material.map = new CanvasTexture(canvas);
                this.material.map.anisotropy = threeLoader.anisotropy;
                this.material.alphaTest = 0.1;
                this.material.needsUpdate = true;
                await new Promise(resolve => requestAnimationFrame(resolve));
                this.visible = true;
                this.div.remove();
                resolve();
            });

        });

        this.dispatchEvent({ type: "loaded" } as never);
    }


}